# -*- coding: utf-8 -*-
# ===========================================
# @Time    : 2021/8/24 下午12:04
# @Author  : shutao
# @FileName: build.py
# @remark  : 
# 
# @Software: PyCharm
# Github 　： https://github.com/NameLacker
# ===========================================

import importlib
import os
import sys


def get_exp_by_file(exp_file):
    try:
        sys.path.append(os.path.dirname(exp_file))
        current_exp = importlib.import_module(os.path.basename(exp_file).split(".")[0])
        exp = current_exp.Exp()
    except Exception:
        raise ImportError("{} doesn't contains class named 'Exp'".format(exp_file))
    return exp


def _get_exps_filedict():
    filedict = {}
    exps_file = "../exps" if os.access("../exps", os.F_OK) else "exps"
    for file in os.listdir(exps_file):
        if file.split('.')[-1] != 'py':
            continue
        filedict[file.split('.')[0]] = file
    return filedict


def get_exp_by_name(exp_name):
    import modules

    path = os.path.dirname(os.path.dirname(modules.__file__))
    filedict = _get_exps_filedict()
    filename = filedict[exp_name]
    exp_path = os.path.join(path, "exps", filename)
    return get_exp_by_file(exp_path)


def get_exp(exp_file, exp_name):
    """
    get Exp object by file or name. If exp_file or exp_name are both provided, then get Exp by file
    :param exp_file:
    :param exp_name:
    :return:
    """
    assert (exp_file is not None or exp_name is not None), "plz provide exp file or exp name."
    if exp_file is not None:
        return get_exp_by_file(exp_file)
    else:
        return get_exp_by_name(exp_name)
